package com.beiing.tianshuai.tianshuai.huodong;

import android.annotation.SuppressLint;
import android.app.Dialog;
import android.content.ClipData;
import android.content.ClipboardManager;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.content.ContextCompat;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.PopupMenu;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.SimpleItemAnimator;
import android.support.v7.widget.Toolbar;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.Gravity;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.animation.AlphaAnimation;
import android.view.animation.Animation;
import android.view.inputmethod.InputMethodManager;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RadioButton;
import android.widget.RelativeLayout;
import android.widget.ScrollView;
import android.widget.TextView;

import com.beiing.tianshuai.tianshuai.R;
import com.beiing.tianshuai.tianshuai.adapter.ActivitySkuTagAdapter;
import com.beiing.tianshuai.tianshuai.adapter.HuoDongCommentAdapter;
import com.beiing.tianshuai.tianshuai.app.AppConstant;
import com.beiing.tianshuai.tianshuai.app.HttpRequestConstant;
import com.beiing.tianshuai.tianshuai.base.BaseActivity;
import com.beiing.tianshuai.tianshuai.entity.ActiveInfoBean;
import com.beiing.tianshuai.tianshuai.entity.ActiveReplyBean;
import com.beiing.tianshuai.tianshuai.entity.FollowBean;
import com.beiing.tianshuai.tianshuai.entity.HuoDongCollectBean;
import com.beiing.tianshuai.tianshuai.entity.HuoDongCommentBean;
import com.beiing.tianshuai.tianshuai.entity.HuoDongDetailBean;
import com.beiing.tianshuai.tianshuai.entity.HuoDongPraiseBean;
import com.beiing.tianshuai.tianshuai.entity.UserInfoBean;
import com.beiing.tianshuai.tianshuai.fragment.EmotionCompleteFragment;
import com.beiing.tianshuai.tianshuai.huodong.adapter.ApplyMembersListAdapter;
import com.beiing.tianshuai.tianshuai.huodong.presenter.HuoDongDetailPresenter;
import com.beiing.tianshuai.tianshuai.huodong.view.HuoDongDetailViewImpl;
import com.beiing.tianshuai.tianshuai.mine.ui.LoginActivity;
import com.beiing.tianshuai.tianshuai.mine.ui.NewPersonalIndexActivity;
import com.beiing.tianshuai.tianshuai.nim.session.SessionHelper;
import com.beiing.tianshuai.tianshuai.util.AppUtils;
import com.beiing.tianshuai.tianshuai.util.DateUtil;
import com.beiing.tianshuai.tianshuai.util.DisplayUtil;
import com.beiing.tianshuai.tianshuai.util.GlobalOnItemClickManagerUtils;
import com.beiing.tianshuai.tianshuai.util.LogUtils;
import com.beiing.tianshuai.tianshuai.util.NetBitmapUtils;
import com.beiing.tianshuai.tianshuai.util.SPUtils;
import com.beiing.tianshuai.tianshuai.widget.ActionSheet;
import com.beiing.tianshuai.tianshuai.widget.AmountView;
import com.beiing.tianshuai.tianshuai.widget.CustomDialog;
import com.beiing.tianshuai.tianshuai.widget.CustomProgressDialog;
import com.beiing.tianshuai.tianshuai.widget.ShowImageWebView;
import com.beiing.tianshuai.tianshuai.widget.TranslucentScrollView;
import com.bumptech.glide.Glide;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.bumptech.glide.request.RequestOptions;
import com.hhl.library.FlowTagLayout;
import com.hhl.library.OnTagSelectListener;
import com.qmuiteam.qmui.widget.QMUIRadiusImageView;
import com.tencent.connect.common.Constants;
import com.tencent.connect.share.QQShare;
import com.tencent.connect.share.QzoneShare;
import com.tencent.mm.opensdk.modelmsg.SendMessageToWX;
import com.tencent.mm.opensdk.modelmsg.WXMediaMessage;
import com.tencent.mm.opensdk.modelmsg.WXWebpageObject;
import com.tencent.mm.opensdk.openapi.IWXAPI;
import com.tencent.mm.opensdk.openapi.WXAPIFactory;
import com.tencent.open.utils.ThreadManager;
import com.tencent.tauth.IUiListener;
import com.tencent.tauth.Tencent;
import com.tencent.tauth.UiError;
import com.tianshuai.easypopup.EasyPopup;

import java.io.UnsupportedEncodingException;
import java.net.URISyntaxException;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.text.MessageFormat;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import cn.bingoogolapple.bgabanner.BGABanner;
import cn.bingoogolapple.bgabanner.BGAOnNoDoubleClickListener;
import me.shihao.library.XStatusBarHelper;

/**
 * 活动详情
 *
 * @author LZQ
 * @date 2017/7/23
 */

public class ActivitiesDetailActivity extends BaseActivity implements HuoDongDetailViewImpl, View.OnClickListener {

    /**
     * 活动的跟视图
     */
    @BindView(R.id.rl_root_view)
    RelativeLayout rlRootView;

    /**
     * 活动详情页面轮播图
     */
    @BindView(R.id.huodong_detail_banner)
    BGABanner hdBanner;

    /**
     * 活动发起者头像
     */
    @BindView(R.id.huodong_detail_header)
    QMUIRadiusImageView hdHeader;

    /**
     * 关注活动发起者 按钮
     */
    @BindView(R.id.huodong_detail_attention)
    TextView hdAttention;

    /**
     * 活动标题
     */
    @BindView(R.id.activity_detail_title)
    TextView hdDetailTitle;

    /**
     * 活动时间
     */
    @BindView(R.id.huodong_detail_time)
    TextView hdDetailTime;

    /**
     * 活动地点
     */
    @BindView(R.id.huodong_detail_location)
    TextView hdDetailLocation;

    /**
     * 活动报名价格
     */
    @BindView(R.id.huodong_detail_payment)
    TextView hdDetailPayment;

    /**
     * 活动详情网页
     */
    @BindView(R.id.huodong_detail_web)
    ShowImageWebView hdWebView;

    /**
     * 底部按钮分割线
     */
    @BindView(R.id.bottom_split)
    View splitView;

    /**
     * 底部按钮
     */
    @BindView(R.id.ll_bottom_menu)
    LinearLayout llBottomMenu;

    /**
     * 底部在线咨询  按钮
     */
    @BindView(R.id.huodong_detail_consult)
    TextView hdDetailConsult;

    /**
     * 底部收藏  文字
     */
    @BindView(R.id.tv_is_followed)
    TextView tvIsFollowed;

    /**
     * 底部评论  按钮
     */
    @BindView(R.id.huodong_detail_comment)
    TextView hdDetailComment;

    /**
     * 底部报名  按钮
     */
    @BindView(R.id.btn_apply_for)
    TextView hdDetailSign;

    /**
     * 滑动包裹容器
     */
    @BindView(R.id.tsv_scroll_view)
    TranslucentScrollView mScrollView;

    /**
     * 顶部ToolBar
     */
    @BindView(R.id.toolbar_active)
    Toolbar mToolBar;

    /**
     * 顶部ToolBar返回
     */
    @BindView(R.id.toolbar_iv_back)
    ImageView mToolbarBack;

    /**
     * 顶部ToolBar标题
     */
    @BindView(R.id.toolbar_tv_title)
    TextView mToolbarTitle;

    /**
     * 顶部ToolBar分享
     */
    @BindView(R.id.toolbar_iv_share)
    ImageView mToolBarShare;

    /**
     * 顶部ToolBar下面横线
     */
    @BindView(R.id.toolbar_underline)
    View mToolbarUnderLine;

    /**
     * 评论列表
     */
    @BindView(R.id.huodong_detail_recycler)
    RecyclerView mRecyclerView;

    /**
     * 报名人数
     */
    @BindView(R.id.tv_apply_count)
    TextView mTvApplyCount;

    /**
     * 报名用户列表
     */
    @BindView(R.id.rv_apply_members)
    RecyclerView mRvApplyMembers;

    /**
     * 评论输人框线性布局
     */
    @BindView(R.id.huodong_detail_ll_comment)
    LinearLayout mLlComment;

    /**
     * 评论输入框
     */
    @BindView(R.id.huodong_detail_edit)
    EditText mCommentEdit;

    /**
     * 评论发送
     */
    @BindView(R.id.huodong_detail_send)
    TextView mCommentSend;

    /**
     * 最新评论
     */
    @BindView(R.id.huodong_comment)
    TextView mTvActivityComment;

    /**
     * 发布时间
     */
    @BindView(R.id.detail_time)
    TextView detailTime;

    /**
     * 阅读次数
     */
    @BindView(R.id.detail_view)
    TextView detailView;

    /**
     * 分享次数
     */
    @BindView(R.id.detail_share)
    TextView detailShare;

    /**
     * 点赞
     */
    @BindView(R.id.detail_praise)
    TextView detailPraise;

    /**
     * 加载中白色view
     */
    @BindView(R.id.loading_background)
    View mLoadingBackground;

    /**
     * 表情图标
     */
    @BindView(R.id.iv_face)
    ImageView ivFace;

    /**
     * 键盘图标
     */
    @BindView(R.id.iv_keyboard)
    ImageView ivKeyBoard;

    /**
     * 表情面板
     */
    @BindView(R.id.fl_emotionview_main)
    FrameLayout mEmotionView;

    private static final String TAG = "ActivitiesDetail";
    private ApplyMembersListAdapter mApplyMembersListAdapter;
    private String activityId = null;
    private String uid;
    private String mToUid;
    private HuoDongCommentAdapter mAdapter;
    private List<HuoDongDetailBean.DataBean.CommentBean> commentBeanList;
    private HuoDongDetailBean.DataBean.ActiveBean mActivityBean;
    private HuoDongDetailPresenter mPresenter;
    private InputMethodManager imm;
    private String url;
    private Dialog bottomDialog;
    private Bitmap thumb;
    private Drawable toPraise, isPraised;
    private MyIUiListener mIUiListener;
    private Tencent mTencent;
    private AlphaAnimation mHideAnimation;
    private WebSettings settings;
    private String bookingUrl;
    private int retryConnect;
    private PopupMenu mPopupMenu;

    private int sendType;
    private String cid;
    private String tUid;
    private String tName;
    private String comment;
    private int replyType;
    private String replyRid;

    private EmotionCompleteFragment emotionCompleteFragment;
    private GlobalOnItemClickManagerUtils globalOnItemClickManagerUtils;
    private boolean emotionLayoutIsShow;

    /**
     * sku popup window
     */
    private EasyPopup mTicketSkuPopupWindow;

    /**
     * the parent view of the popup window
     */
    private View mRootView;

    @Override
    protected int getLayoutId() {
        return R.layout.activity_activities_detail;
    }

    @SuppressLint("SetJavaScriptEnabled")
    @Override
    protected void init() {
        imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
        mTencent = Tencent.createInstance("1106377834", getApplicationContext());
        mIUiListener = new MyIUiListener();
        initStatusBar();
        CustomProgressDialog.showLoading(mContext, "", true);
        CustomProgressDialog.setCancelListener(new DialogInterface.OnCancelListener() {
            @Override
            public void onCancel(DialogInterface dialog) {
                finish();
            }
        });
        initRecyclerView();
        initData();
        initPresenter();
        initListener();
        initEmotionMainFragment();
    }

    private void initEmotionMainFragment() {
        globalOnItemClickManagerUtils = GlobalOnItemClickManagerUtils.getInstance(mContext);
        globalOnItemClickManagerUtils.attachToEditText(mCommentEdit);
        emotionCompleteFragment = new EmotionCompleteFragment();
        FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
        transaction.add(R.id.fl_emotionview_main, emotionCompleteFragment);
        transaction.commit();
    }

    private void initPresenter() {
        mPresenter = new HuoDongDetailPresenter(this);
        mPresenter.getHuoDongDetail(uid, activityId);
    }

    private void initRecyclerView() {
        // 初始化报名用户头像的RecyclerView
        LinearLayoutManager applyMembersLinearLayoutManager = new LinearLayoutManager(mContext, LinearLayoutManager.HORIZONTAL, false);
        mRvApplyMembers.setLayoutManager(applyMembersLinearLayoutManager);

        // 初始化报名用户列表的adapter
        mApplyMembersListAdapter = new ApplyMembersListAdapter(mContext);
        mRvApplyMembers.setAdapter(mApplyMembersListAdapter);

        commentBeanList = new ArrayList<>();
        LinearLayoutManager manager = new LinearLayoutManager(mContext, LinearLayoutManager.VERTICAL, false);
        mRecyclerView.setLayoutManager(manager);
        mRecyclerView.setNestedScrollingEnabled(false);
        ((SimpleItemAnimator) mRecyclerView.getItemAnimator()).setSupportsChangeAnimations(false);
        mAdapter = new HuoDongCommentAdapter(mContext, commentBeanList);
        mRecyclerView.setAdapter(mAdapter);

        mAdapter.setOnItemViewClickListener(new HuoDongCommentAdapter.OnItemViewClickListener() {
            @Override
            public void onItemClick(View view, int position, HuoDongDetailBean.DataBean.CommentBean commentBean) {
//                showPopupMenu(view, position, commentBean);
                mLlComment.setVisibility(View.VISIBLE);
                llBottomMenu.setVisibility(View.GONE);
                splitView.setVisibility(View.GONE);
                mCommentEdit.setFocusable(true);
                mCommentEdit.setFocusableInTouchMode(true);
                mCommentEdit.requestFocus();
                imm.toggleSoftInput(0, InputMethodManager.HIDE_NOT_ALWAYS);
                //弹出软件隐藏表情面板
                mEmotionView.setVisibility(View.GONE);
                emotionLayoutIsShow = false;
                switch (commentBean.getTableType()) {
                    case "0":
                        mCommentEdit.setHint("回复" + commentBean.getName());
                        cid = commentBean.getId();
                        tUid = commentBean.getUid();
                        tName = commentBean.getName();
                        comment = commentBean.getContent();
                        replyType = 0;
                        break;
                    case "1":
                        mCommentEdit.setHint("回复" + commentBean.getFName());
                        cid = commentBean.getCid();
                        tUid = commentBean.getFormUid();
                        tName = commentBean.getFName();
                        comment = commentBean.getContent();
                        replyType = 1;
                        replyRid = commentBean.getId();
                        break;
                    default:
                        break;
                }
                sendType = 1;
            }

            @Override
            public void onItemViewClick(View view, int positon) {
                switch (view.getId()) {
                    case R.id.huodong_comment_head:
                        Intent intent = new Intent(mContext, NewPersonalIndexActivity.class);
                        switch (commentBeanList.get(positon).getTableType()) {
                            case "0":
                                intent.putExtra("uid", commentBeanList.get(positon).getUid());
                                break;
                            case "1":
                                intent.putExtra("uid", commentBeanList.get(positon).getFormUid());
                                break;
                            default:
                                break;
                        }
                        startActivity(intent);
                        break;
                    case R.id.huodong_comment_praise:
                        switch (commentBeanList.get(positon).getTableType()) {
                            case "0":
                                mPresenter.praiseComment(uid, activityId, commentBeanList.get(positon).getId(), positon);
                                break;
                            case "1":
                                mPresenter.praiseReply(uid, activityId, commentBeanList.get(positon).getCid(), commentBeanList.get(positon).getId(), commentBeanList.get(positon).getFormUid(), positon);
                                break;
                            default:
                                break;
                        }
                        break;
                    default:
                        break;
                }
            }
        });

        mAdapter.setOnTextClickListener(new HuoDongCommentAdapter.OnTextClickListener() {
            @Override
            public void onTextClick(View view, int position, int type, HuoDongDetailBean.DataBean.CommentBean commentBean) {
                Intent intent = new Intent(mContext, NewPersonalIndexActivity.class);
                intent.putExtra("uid", commentBean.getToUid());
                startActivity(intent);
            }
        });

        mAdapter.setOnItemLongClickListener(new HuoDongCommentAdapter.OnItemLongClickListener() {
            @Override
            public void onItemLongClick(View view, int position, HuoDongDetailBean.DataBean.CommentBean commentBean) {
                showPopupMenu(view, position, commentBean);
            }
        });
    }

    private void showPopupMenu(View view, final int position, final HuoDongDetailBean.DataBean.CommentBean commentBean) {
        mPopupMenu = new PopupMenu(mContext, view, Gravity.END);
        mPopupMenu.getMenuInflater().inflate(R.menu.comment_click_menu, mPopupMenu.getMenu());
        switch (commentBean.getTableType()) {
            case "0":
                if (commentBean.getUid().equals(uid)) {
                    mPopupMenu.getMenu().findItem(R.id.item_delete).setVisible(true);
                } else {
                    mPopupMenu.getMenu().findItem(R.id.item_delete).setVisible(false);
                }
                break;
            case "1":
                if (commentBean.getFormUid().equals(uid)) {
                    mPopupMenu.getMenu().findItem(R.id.item_delete).setVisible(true);
                } else {
                    mPopupMenu.getMenu().findItem(R.id.item_delete).setVisible(false);
                }
                break;
            default:
                break;
        }

        mPopupMenu.show();
        mPopupMenu.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() {
            @Override
            public boolean onMenuItemClick(MenuItem menuItem) {
                switch (menuItem.getItemId()) {
                    case R.id.item_copy:
                        ClipboardManager cm = (ClipboardManager) getSystemService(Context.CLIPBOARD_SERVICE);
                        try {
                            if (cm != null) {
                                ClipData content = ClipData.newPlainText("content", URLDecoder.decode(commentBean.getContent(), "UTF-8"));
                                cm.setPrimaryClip(content);
                            }
                        } catch (UnsupportedEncodingException e) {
                            e.printStackTrace();
                        }
                        showShortText("已复制");
                        break;
                    case R.id.item_delete:
                        switch (commentBean.getTableType()) {
                            case "0":
                                mPresenter.deleteComment(commentBean.getId());
                                break;
                            case "1":
                                mPresenter.deleteReply(activityId, commentBean.getId(), uid);
                                break;
                            default:
                                break;
                        }
                        mAdapter.deleteItem(position);
                        break;
                    default:
                        break;
                }
                return false;
            }
        });
    }

    private void initStatusBar() {
        mToolBar.setPadding(0, XStatusBarHelper.getStatusBarHeight(mContext), 0, 0);
        XStatusBarHelper.immersiveStatusBar(this, 0);
    }

    private void initData() {
        Intent intent = getIntent();
        activityId = intent.getStringExtra("active_id");
        uid = SPUtils.getString(mContext, "uid", null);

        toPraise = ContextCompat.getDrawable(mContext, R.mipmap.praise_gray_line);
        isPraised = ContextCompat.getDrawable(mContext, R.mipmap.praise_red_solid);
    }

    /**
     * 显示活动详情页面
     *
     * @param huoDongDetailBean 活动详情数据
     */
    @SuppressLint("SetJavaScriptEnabled")
    @Override
    public void showHuoDongDetail(HuoDongDetailBean.DataBean huoDongDetailBean) {
        mActivityBean = huoDongDetailBean.getActive().get(0);
        int isCollect = huoDongDetailBean.getIsCollect();
        int isThing = huoDongDetailBean.getIsThing();
        mToolbarTitle.setText(mActivityBean.getUname());

        //1为已收藏，2为没收藏
        if (isCollect == 1) {
            tvIsFollowed.setText("已收藏");
            Drawable followed = ContextCompat.getDrawable(mContext, R.mipmap.y_like);
            if (followed != null) {
                followed.setBounds(0, 0, followed.getMinimumWidth(), followed.getMinimumHeight());
                tvIsFollowed.setCompoundDrawables(null, followed, null, null);
            }
        } else {
            tvIsFollowed.setText("收藏");
            Drawable followed = ContextCompat.getDrawable(mContext, R.mipmap.like_gray_solid);
            if (followed != null) {
                followed.setBounds(0, 0, followed.getMinimumWidth(), followed.getMinimumHeight());
                tvIsFollowed.setCompoundDrawables(null, followed, null, null);
            }
        }

        //1为已赞，2为没赞
        if (isThing == 1) {
            detailPraise.setCompoundDrawablesWithIntrinsicBounds(isPraised, null, null, null);
            detailPraise.setText("已赞");
        } else {
            detailPraise.setCompoundDrawablesWithIntrinsicBounds(toPraise, null, null, null);
            detailPraise.setText("赞");
        }

        //根据库存修改报名按钮的状态
        int quantity = Integer.valueOf(mActivityBean.getCount());
        int backgroundColor;
        if (quantity > 0) {
            backgroundColor = ContextCompat.getColor(mContext, R.color.color_blue_67a0ff);
            hdDetailSign.setText("我要报名");
        } else {
            backgroundColor = ContextCompat.getColor(mContext, R.color.color_grey_999999);
            hdDetailSign.setText("已售罄");
        }
        hdDetailSign.setBackgroundColor(backgroundColor);

        // 报名人数
        mTvApplyCount.setText(MessageFormat.format("已报名{0}", huoDongDetailBean.getOrdersCount().get(0).getSumcount52()));
        // 报名用户头像列表
        List<HuoDongDetailBean.DataBean.ActiveBean.ActiveOrdersUserBean> activeOrdersUser = mActivityBean.getActiveOrdersUser();
        if (!activeOrdersUser.isEmpty()) {
            mApplyMembersListAdapter.appendData(activeOrdersUser);
        }

        if (huoDongDetailBean.getComment().size() == 0) {
            mTvActivityComment.setText("还没有评论，来抢个沙发吧！");
        } else {
            mTvActivityComment.setText("最新评论");
        }
        detailView.setText(mActivityBean.getView());
        detailShare.setText(mActivityBean.getShare());
        if (mActivityBean.getThreeUrl() != null) {
            bookingUrl = mActivityBean.getThreeUrl();
        }

        //关闭轮播
        hdBanner.setAutoPlayAble(false);
        hdBanner.setAdapter(new BGABanner.Adapter<ImageView, String>() {

            @Override
            public void fillBannerItem(BGABanner banner, ImageView itemView, String model, int position) {
                Glide.with(mContext.getApplicationContext())
                        .load(model)
                        .into(itemView);
            }
        });
        List<String> bannersUrl = new ArrayList<>();
        List<String> bannersTip = new ArrayList<>();
        for (int i = 0; i < 1; i++) {
            bannersUrl.add(HttpRequestConstant.ACTIVITY_PIC_HEAD + mActivityBean.getCover());
            bannersTip.add("");
        }
        hdBanner.setData(bannersUrl, bannersTip);
        Glide.with(getApplicationContext())
                .load("".equals(mActivityBean.getPhoto()) ? R.mipmap.default_avatar :
                        HttpRequestConstant.USER_PIC_HEAD + mActivityBean.getPhoto())
                .into(hdHeader);
        hdDetailTitle.setText(mActivityBean.getStrech());
        hdDetailTime.setText(MessageFormat.format("{0} - {1}",
                DateUtil.timeStamp2Date(mActivityBean.getActionTime(), "yyyy-MM-dd HH:mm"),
                DateUtil.timeStamp2Date(mActivityBean.getExitTime(), "yyyy-MM-dd HH:mm")));

        // 设置地址
        String location = mActivityBean.getLocation();
        if (!TextUtils.isEmpty(location)) {
            hdDetailLocation.setVisibility(View.VISIBLE);
            hdDetailLocation.setText(location);
        } else {
            hdDetailLocation.setVisibility(View.GONE);
        }

        hdDetailPayment.setText("0".equals(mActivityBean.getMuch()) ? "免费" : "￥" + mActivityBean.getMuch());

        mToUid = mActivityBean.getUid();
        url = "http://www.tianshuai.com.cn/index.php/Home/Active/page2/id/" + mActivityBean.getId();
        mPresenter.isFollowed(uid, mToUid);

        settings = hdWebView.getSettings();
        // 加快界面加载速度，等页面finish再加载图片
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            settings.setLoadsImagesAutomatically(true);
        } else {
            settings.setLoadsImagesAutomatically(false);
        }
        settings.setJavaScriptEnabled(true);
        settings.setDefaultTextEncodingName("UTF-8");
        settings.setSupportZoom(true);
        hdWebView.setWebViewClient(new WebViewClient() {

            @Override
            public boolean shouldOverrideUrlLoading(WebView view, String url) {
                // url为你要链接的地址
                Uri uri = Uri.parse(url);
                Intent intent = new Intent(Intent.ACTION_VIEW, uri);
                startActivity(intent);
                return true;
            }

            @Override
            public void onPageFinished(WebView view, String url) {
                hdWebView.setImageClickListener();
                hdWebView.parseHTML(view);
                // 加快界面加载速度，等页面finish再加载图片
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
                    settings.setLoadsImagesAutomatically(true);
                } else {
                    settings.setLoadsImagesAutomatically(false);
                }
            }

            @Override
            public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
                showShortText("请检查您的网络设置");
            }
        });
        hdWebView.loadUrl(HttpRequestConstant.MAIN_REQUEST_HEAD + "Active/part_app/id/" + activityId);
        hdWebView.setWebChromeClient(new WebChromeClient() {
            @Override
            public void onProgressChanged(WebView view, int newProgress) {
                if (newProgress == 100) {
                    CustomProgressDialog.stopLoading();
                }
                super.onProgressChanged(view, newProgress);
            }
        });
    }

    @SuppressLint("ClickableViewAccessibility")
    private void initListener() {
        mApplyMembersListAdapter.setListener(new ApplyMembersListAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(HuoDongDetailBean.DataBean.ActiveBean.ActiveOrdersUserBean bean, int position) {
                String uid = bean.getUid();
                if (!TextUtils.isEmpty(uid)) {
                    Intent intent = new Intent(mContext, NewPersonalIndexActivity.class);
                    intent.putExtra("uid", uid);
                    startActivity(intent);
                } else {
                    showShortText("该用户不存在");
                }
            }
        });

        //dialog dismiss listener
        CustomProgressDialog.setListener(new CustomProgressDialog.OnDismiss() {
            @Override
            public void onDismissListener() {
                setHideAnimation(mLoadingBackground);
            }
        });

        mScrollView.setOnScrollChangedListener(new TranslucentScrollView.OnScrollChangedListener() {
            @Override
            public void onScrollChanged(ScrollView who, int l, int t, int oldl, int oldt, Boolean isBottom) {
                //变化率
                int scrollY = who.getScrollY();
                int headerHeight = (int) (DisplayUtil.getMobileHeight(mContext) * 0.4);
                float minHeaderHeight = getResources().getDimension(R.dimen.custom_action_bar_default_height_material);
                //Toolbar与header高度的差值
                float headerBarOffsetY = headerHeight - minHeaderHeight;
                float offset = 1 - Math.max((headerBarOffsetY - scrollY) / headerBarOffsetY, 0.00f);
                //Toolbar背景色透明度
                if (scrollY >= 0) {
                    int transformColor = Color.argb((int) (offset * 255), 255, 255, 255);
                    LogUtils.i(String.valueOf(offset), ActivitiesDetailActivity.class.getName());
                    mToolBar.setBackgroundColor(transformColor);
                    mToolbarUnderLine.setBackgroundColor(Color.argb((int) (offset * 255), 239, 239, 239));
                }
            }
        });

        mScrollView.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View view, MotionEvent motionEvent) {
                mCommentEdit.setFocusable(false);
                hdWebView.requestFocus();
                mCommentEdit.setHint("说几句");
                mLlComment.setVisibility(View.GONE);
                llBottomMenu.setVisibility(View.VISIBLE);
                splitView.setVisibility(View.VISIBLE);
                try {
                    imm.hideSoftInputFromWindow(getWindow().getDecorView().getWindowToken(), 0);
                } catch (Exception e) {
                    LogUtils.e("this window has bean destroyed", TAG);
                    e.printStackTrace();
                }
                return false;
            }
        });

        //输入框点击监听
        mCommentEdit.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View view, MotionEvent motionEvent) {
                if (TextUtils.isEmpty(UserInfoBean.getUid(mContext))) {
                    startActivity(new Intent(mContext, LoginActivity.class));
                } else {
                    mCommentEdit.setFocusable(true);
                    mCommentEdit.setFocusableInTouchMode(true);
                    mCommentEdit.requestFocus();
                    mEmotionView.setVisibility(View.GONE);
                    ivKeyBoard.setVisibility(View.GONE);
                    ivFace.setVisibility(View.VISIBLE);
                    emotionLayoutIsShow = false;
                }
                return false;
            }
        });

        tvIsFollowed.setOnClickListener(this);
        mToolbarBack.setOnClickListener(this);
        mToolBarShare.setOnClickListener(this);
        hdAttention.setOnClickListener(this);
        hdDetailConsult.setOnClickListener(this);
        hdDetailComment.setOnClickListener(this);
        hdDetailSign.setOnClickListener(this);
        mCommentSend.setOnClickListener(this);
        detailShare.setOnClickListener(this);
        detailPraise.setOnClickListener(this);

        // 活动地点
        hdDetailLocation.setOnClickListener(new BGAOnNoDoubleClickListener() {
            @Override
            public void onNoDoubleClick(View v) {
                String keyword = hdDetailLocation.getText().toString();
                ActionSheet actionSheet = new ActionSheet(mContext);
                actionSheet.builder()
                        .setCancelable(true)
                        .setCanceledOnTouchOutside(true)
                        .addSheetItem("腾讯地图", ActionSheet.SheetItemColor.Blue, new onClickSheetItem(keyword))
                        .addSheetItem("百度地图", ActionSheet.SheetItemColor.Blue, new onClickSheetItem(keyword))
                        .addSheetItem("高德地图", ActionSheet.SheetItemColor.Blue, new onClickSheetItem(keyword))
                        .show();
            }
        });

        //输入框输入监听
        mCommentEdit.addTextChangedListener(new TextWatcher() {

            @Override
            public void beforeTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                if (s.length() > 0 && !"".equals(s.toString().trim())) {
                    //有文字内容
                    mCommentSend.setBackgroundResource(R.drawable.publish_blue);
                    mCommentSend.setClickable(true);
                } else {
                    //没有文字内容
                    mCommentSend.setBackgroundResource(R.drawable.publish_gray);
                    mCommentSend.setClickable(false);
                }
            }
        });

        ivFace.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                ivFace.setVisibility(View.GONE);
                ivKeyBoard.setVisibility(View.VISIBLE);
                emotionLayoutIsShow = true;
                imm.hideSoftInputFromWindow(getWindow().getDecorView().getWindowToken(), 0);
                mEmotionView.setVisibility(View.VISIBLE);
            }
        });

        ivKeyBoard.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                mEmotionView.setVisibility(View.GONE);
                ivKeyBoard.setVisibility(View.GONE);
                ivFace.setVisibility(View.VISIBLE);
                imm.toggleSoftInput(0, InputMethodManager.HIDE_NOT_ALWAYS);
                mCommentEdit.setFocusable(true);
                mCommentEdit.setFocusableInTouchMode(true);
                mCommentEdit.requestFocus();
            }
        });
    }

    public void setHideAnimation(final View view) {
        if (null == view) {
            return;
        }

        if (null != mHideAnimation) {
            mHideAnimation.cancel();
        }
        // 监听动画结束的操作
        mHideAnimation = new AlphaAnimation(1.0f, 0.0f);
        mHideAnimation.setDuration(888);
        mHideAnimation.setFillAfter(true);
        mHideAnimation.setAnimationListener(new Animation.AnimationListener() {

            @Override
            public void onAnimationStart(Animation arg0) {

            }

            @Override
            public void onAnimationRepeat(Animation arg0) {

            }

            @Override
            public void onAnimationEnd(Animation arg0) {
                view.setVisibility(View.GONE);
            }
        });
        view.startAnimation(mHideAnimation);
    }

    @Override
    protected void onNewIntent(Intent intent) {
        //每次重新到前台就主动更新intent并保存，之后就能获取到最新的intent
        setIntent(intent);
        super.onNewIntent(intent);
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.toolbar_iv_back:
                finish();
                break;
            case R.id.toolbar_iv_share:
                showShareDialog();
                break;
            case R.id.huodong_detail_attention:
                //关注活动发布者
                if (TextUtils.isEmpty(UserInfoBean.getUid(mContext))) {
                    startActivity(new Intent(mContext, LoginActivity.class));
                } else {
                    mPresenter.setFollowed(uid, mToUid);
                }
                break;
            case R.id.huodong_detail_consult:
                //在线咨询
                if (!TextUtils.isEmpty(UserInfoBean.getUid(mContext))) {
                    if (!TextUtils.isEmpty(mActivityBean.getUid())) {
                        SessionHelper.startP2PSession(mContext, mActivityBean.getUid());
                        SPUtils.put(mContext, "nickname" + mActivityBean.getUid(), mActivityBean.getUname());
                    }
                } else {
                    toLogin();
                }
                break;
            case R.id.tv_is_followed:
                //活动收藏
                if (TextUtils.isEmpty(UserInfoBean.getUid(mContext))) {
                    startActivity(new Intent(mContext, LoginActivity.class));
                } else {
                    mPresenter.collectHuoDong(uid, activityId);
                }
                break;
            case R.id.huodong_detail_comment:
                //活动评论
                if (TextUtils.isEmpty(UserInfoBean.getUid(mContext))) {
                    startActivity(new Intent(mContext, LoginActivity.class));
                } else {
                    mLlComment.setVisibility(View.VISIBLE);
                    llBottomMenu.setVisibility(View.GONE);
                    mEmotionView.setVisibility(View.GONE);
                    ivKeyBoard.setVisibility(View.GONE);
                    ivFace.setVisibility(View.VISIBLE);
                    splitView.setVisibility(View.GONE);
                    mCommentEdit.setFocusable(true);
                    mCommentEdit.setFocusableInTouchMode(true);
                    mCommentEdit.requestFocus();
                    mCommentEdit.findFocus();
                    imm.toggleSoftInput(0, InputMethodManager.HIDE_NOT_ALWAYS);
                    sendType = 0;
                }
                break;
            case R.id.btn_apply_for:
                // 活动报名
                int quantity = Integer.valueOf(mActivityBean.getCount());
                if (quantity > 0) {
                    showSkuPopupWindow();
                } else {
                    showShortText("来晚啦，票已经被抢光了");
                }
//                if (TextUtils.isEmpty(UserInfoBean.getUid(mContext))) {
//                    startActivity(new Intent(mContext, LoginActivity.class));
//                } else if (mActivityBean.getIsThree().equals("1")) {
//                    // 判断是否为第三方票务，如果是第三方票务跳转到指定购买界面
//                    showBookingDialog();
//                } else if (Integer.parseInt(mActivityBean.getCount()) > 0) {
//                    ActiveInfoBean activeInfoBean = new ActiveInfoBean();
//                    activeInfoBean.setAid(mActivityBean.getId());
//                    activeInfoBean.setTitle(mActivityBean.getStrech());
//                    activeInfoBean.setCover(mActivityBean.getCover());
//                    activeInfoBean.setPrice(mActivityBean.getMuch());
//                    activeInfoBean.setRestCount(mActivityBean.getCount());
//                    Intent orderIntent = new Intent(mContext, ActivitiesApplyForActivity.class);
//                    Bundle bundle = new Bundle();
//                    bundle.putSerializable("activeInfo", activeInfoBean);
//                    orderIntent.putExtras(bundle);
//                    startActivity(orderIntent);
//                } else {
//                    showShortText("暂时没有多于的票了");
//                }
                break;
            case R.id.huodong_detail_send:
                if (!TextUtils.isEmpty(mCommentEdit.getText().toString().trim())) {
                    String contentUTF8;
                    try {
                        contentUTF8 = URLEncoder.encode(mCommentEdit.getText().toString(), "UTF-8");
                    } catch (UnsupportedEncodingException e) {
                        contentUTF8 = mCommentEdit.getText().toString();
                        e.printStackTrace();
                    }
                    switch (sendType) {
                        case 0:
                            mPresenter.commentHuoDong(activityId, uid, contentUTF8, System.currentTimeMillis() / 1000 + "");
                            break;
                        case 1:
                            mPresenter.addReply(activityId, cid, uid, tUid, contentUTF8, comment, replyType, replyRid);
                            break;
                        default:
                            break;
                    }
                    if (imm != null) {
                        imm.hideSoftInputFromWindow(getWindow().getDecorView().getWindowToken(), 0);
                    }
                    mCommentEdit.setText("");
                    mLlComment.setVisibility(View.GONE);
                    mEmotionView.setVisibility(View.GONE);
                }
                break;
            case R.id.detail_share:
                showShareDialog();
                break;
            case R.id.detail_praise:
                if (TextUtils.isEmpty(UserInfoBean.getUid(mContext))) {
                    startActivity(new Intent(mContext, LoginActivity.class));
                } else {
                    mPresenter.praiseHuoDong(uid, activityId);
                }
                break;
            default:
                break;
        }
    }

    /**
     * 弹出规格选择弹窗
     * 选择门票种类和数量
     * 下一步填写用户个人信息
     */
    private void showSkuPopupWindow() {
        if (mTicketSkuPopupWindow == null && mActivityBean != null) {
            initTicketSkuPopupWindow();
        }
        if (mTicketSkuPopupWindow != null) {
            mTicketSkuPopupWindow.showAtLocation(getCurrentFocus(), Gravity.BOTTOM, 0, 0);
        }
    }

    /**
     * 初始化SKU弹窗
     * 绑定数据 设置点击事件
     */
    private void initTicketSkuPopupWindow() {
        mTicketSkuPopupWindow = new EasyPopup(this);
        mTicketSkuPopupWindow.setContentView(R.layout.popwin_ticket_sku, ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT)
                .setAnimationStyle(R.style.AnimBottom)
                //是否允许点击PopupWindow之外的地方消失
                .setFocusAndOutsideEnable(true)
                //允许背景变暗
                .setBackgroundDimEnable(true)
                //变暗的透明度(0-1)，0为完全透明
                .setDimValue(0.4f)
                //变暗的背景颜色
                .setDimColor(Color.BLACK)
                //指定任意 ViewGroup 背景变暗
                .setDimView(rlRootView)
                .createPopup();

        //初始化视图
        View contentView = mTicketSkuPopupWindow.getContentView();
        //缩略图
        QMUIRadiusImageView qivGoodsThumb = contentView.findViewById(R.id.qiv_goods_thumb);
        //单价
        TextView tvGoodsPrice = contentView.findViewById(R.id.tv_goods_price);
        //数量
        TextView tvGoodsQuantity = contentView.findViewById(R.id.tv_goods_quantity);
        //描述
        TextView tvGoodsDescription = contentView.findViewById(R.id.tv_goods_description);
        //关闭按钮
        ImageButton ibCloseDialog = contentView.findViewById(R.id.ib_close_dialog);
        //tickets type selector
        final FlowTagLayout ftlTicketsType = contentView.findViewById(R.id.ftl_tickets_type);
        //数量修改器
        final AmountView amountView = contentView.findViewById(R.id.av_goods_amount);
        //总价
        final TextView tvTotalPrice = contentView.findViewById(R.id.tv_total_price);
        //下一步
        TextView tvNextStep = contentView.findViewById(R.id.tv_next_step);

        //缩略图
        RequestOptions requestOptions = new RequestOptions()
                .diskCacheStrategy(DiskCacheStrategy.ALL)
                .placeholder(R.drawable.img_loading_background)
                .centerCrop();
        Glide.with(mContext.getApplicationContext())
                .load(HttpRequestConstant.ACTIVITY_PIC_HEAD + mActivityBean.getCover())
                .apply(requestOptions)
                .into(qivGoodsThumb);

        //设置商品价格
        String price = mActivityBean.getMuch();
        tvGoodsPrice.setText(TextUtils.equals(price, "0") ? "免费" : "￥" + price);

        //设置数量
        String quantity = mActivityBean.getCount();
        tvGoodsQuantity.setText(TextUtils.equals(quantity, "0") ? "已售罄" : "剩余" + quantity);

        //设置商品描述
        tvGoodsDescription.setText("普通门票");

        //关闭按钮
        ibCloseDialog.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mTicketSkuPopupWindow.dismiss();
            }
        });

        //设置商品规格
        ftlTicketsType.setTagCheckedMode(FlowTagLayout.FLOW_TAG_CHECKED_SINGLE);
        ActivitySkuTagAdapter<String> ticketsTypeTagAdapter = new ActivitySkuTagAdapter<>(mContext);
        ftlTicketsType.setAdapter(ticketsTypeTagAdapter);
        ArrayList<String> ticketsTypeTags = new ArrayList<>();
        ticketsTypeTags.add("普通票");
        ticketsTypeTagAdapter.appendData(ticketsTypeTags);
        ftlTicketsType.setOnTagSelectListener(new OnTagSelectListener() {
            @Override
            public void onItemSelect(FlowTagLayout parent, List<Integer> selectedList) {
                for (int integer : selectedList) {
                    LogUtils.i(parent.getAdapter().getItem(integer).toString(), TAG);
                }
            }
        });

        //设置数量修改器
        amountView.setOnAmountChangeListener(new AmountView.OnAmountChangeListener() {
            @Override
            public void onAmountChange(int amount) {
                tvTotalPrice.setText(String.format("合计：¥%s", amount * Float.valueOf(mActivityBean.getMuch())));
            }
        });
        amountView.setMaxAmount(Integer.parseInt(mActivityBean.getCount()));

        //下一步按钮点击事件
        tvNextStep.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (ftlTicketsType.getSelectedList().isEmpty()) {
                    showShortText("请先选择门票种类");
                } else {
                    String isThree = mActivityBean.getIsThree();
                    if (TextUtils.equals(isThree, "1")) {
                        showBookingDialog();
                    } else {
                        mTicketSkuPopupWindow.dismiss();
                        ActiveInfoBean activeInfoBean = new ActiveInfoBean();
                        activeInfoBean.setAid(mActivityBean.getId());
                        activeInfoBean.setTitle(mActivityBean.getStrech());
                        activeInfoBean.setCover(mActivityBean.getCover());
                        activeInfoBean.setPrice(mActivityBean.getMuch());
                        activeInfoBean.setRestCount(mActivityBean.getCount());
                        activeInfoBean.setAmount(amountView.getAmount());
                        activeInfoBean.setPurchaseMethod(mActivityBean.getPurchaseMethod());
                        ActivitiesApplyForActivity.start(mContext, activeInfoBean);
                    }
                }
            }
        });
    }

    /**
     * 第三方平台购票跳转提示框
     */
    private void showBookingDialog() {
        CustomDialog customDialog = new CustomDialog(mContext, R.style.dialog,
                "此票为第三方平台出售，点击确定跳转到购票地址",
                new CustomDialog.OnCloseListener() {
                    @Override
                    public void onClick(Dialog dialog, boolean confirm) {
                        // url为你要链接的地址
                        Uri uri = Uri.parse(bookingUrl);
                        Intent intent = new Intent(Intent.ACTION_VIEW, uri);
                        mContext.startActivity(intent);
                    }
                }).setTitle("提示");
        customDialog.setCanceledOnTouchOutside(true);
        customDialog.show();
    }

    private void toLogin() {
        Intent intent = new Intent(mContext, LoginActivity.class);
        startActivity(intent);
    }

    private void showShareDialog() {
        bottomDialog = new Dialog(mContext, R.style.BottomDialog);
        View contentView = View.inflate(mContext, R.layout.dialog_interest_detail_bottom_share, null);
        RadioButton wechatFriends = contentView.findViewById(R.id.rb_wechat_friends);
        RadioButton wechatCircle = contentView.findViewById(R.id.rb_wechat_circle);
        RadioButton qqFriends = contentView.findViewById(R.id.rb_qq_friends);
        RadioButton qZone = contentView.findViewById(R.id.rb_qzone);

        wechatFriends.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                //分享到微信好友
                shareToWeChatWithWebPage(mContext, url, mActivityBean.getStrech(), mActivityBean.getLessons(), 0);
                bottomDialog.dismiss();
            }
        });

        wechatCircle.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                //分享到朋友圈
                shareToWeChatWithWebPage(mContext, url, mActivityBean.getStrech(), mActivityBean.getLessons(), 1);
                bottomDialog.dismiss();
            }
        });

        qqFriends.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                //分享到qq好友
                shareToQQ(mActivityBean.getStrech(), mActivityBean.getLessons(), url);
                bottomDialog.dismiss();
            }
        });

        qZone.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                //分享到qq空间
                shareToQZone(mActivityBean.getStrech(), mActivityBean.getLessons(), url);
                bottomDialog.dismiss();
            }
        });

        bottomDialog.setContentView(contentView);
        ViewGroup.LayoutParams layoutParams = contentView.getLayoutParams();
        layoutParams.width = getResources().getDisplayMetrics().widthPixels;
        contentView.setLayoutParams(layoutParams);
        Window window = bottomDialog.getWindow();
        if (window != null) {
            window.setGravity(Gravity.BOTTOM);
            window.setWindowAnimations(R.style.BottomDialog_Animation);
        }

        bottomDialog.show();
        bottomDialog.setCanceledOnTouchOutside(true);
    }

    private void shareToWeChatWithWebPage(Context context, String url, String title, String description, final int scene) {
        final IWXAPI iwxapi = WXAPIFactory.createWXAPI(context, AppConstant.WX_APP_ID);

        if (!iwxapi.isWXAppInstalled()) {
            showShortText("您尚未安装微信");
            return;
        }

        WXWebpageObject wxWebpageObject = new WXWebpageObject();
        wxWebpageObject.webpageUrl = url;
        final WXMediaMessage wxMediaMessage = new WXMediaMessage(wxWebpageObject);
        wxMediaMessage.mediaObject = wxWebpageObject;
        wxMediaMessage.title = title;
        wxMediaMessage.description = description;
//        wxMediaMessage.thumbData =
//                ImageManager.bmpToByteArray(BitmapFactory.decodeResource(context.getResources(), R.mipmap.ic_share_invite), true);
        new Thread(new Runnable() {
            @Override
            public void run() {
                thumb = NetBitmapUtils.getBitmap(HttpRequestConstant.ACTIVITY_PIC_HEAD + mActivityBean.getCover());
                thumb = Bitmap.createScaledBitmap(thumb, 200, 200, true);

                wxMediaMessage.setThumbImage(thumb);

                SendMessageToWX.Req req = new SendMessageToWX.Req();
                req.transaction = String.valueOf(System.currentTimeMillis());
                req.message = wxMediaMessage;
                req.scene = scene;

                iwxapi.sendReq(req);
            }
        }).start();
    }

    private Bundle params;

    private void shareToQQ(String title, String summary, String url) {
        params = new Bundle();
        params.putInt(QQShare.SHARE_TO_QQ_KEY_TYPE, QQShare.SHARE_TO_QQ_TYPE_DEFAULT);
        //标题
        params.putString(QQShare.SHARE_TO_QQ_TITLE, title);
        //摘要
        params.putString(QQShare.SHARE_TO_QQ_SUMMARY, summary);
        //内容地址
        params.putString(QQShare.SHARE_TO_QQ_TARGET_URL, url);

        ThreadManager.getMainHandler().post(new Runnable() {
            @Override
            public void run() {
                mTencent.shareToQQ(ActivitiesDetailActivity.this, params, mIUiListener);
            }
        });
    }

    private Bundle params1;

    private void shareToQZone(String title, String summary, String url) {
        params1 = new Bundle();
        params1.putInt(QzoneShare.SHARE_TO_QZONE_KEY_TYPE, QzoneShare.SHARE_TO_QZONE_TYPE_IMAGE_TEXT);
        //标题
        params1.putString(QzoneShare.SHARE_TO_QQ_TITLE, title);
        //摘要
        params1.putString(QzoneShare.SHARE_TO_QQ_SUMMARY, summary);
        //内容地址
        params1.putString(QzoneShare.SHARE_TO_QQ_TARGET_URL, url);
        params1.putStringArrayList(QzoneShare.SHARE_TO_QQ_IMAGE_URL, new ArrayList<String>());

        ThreadManager.getMainHandler().post(new Runnable() {
            @Override
            public void run() {
                mTencent.shareToQzone(ActivitiesDetailActivity.this, params1, mIUiListener);
            }
        });
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        Tencent.onActivityResultData(requestCode, resultCode, data, mIUiListener);
        if (requestCode == Constants.REQUEST_API) {
            if (resultCode == Constants.REQUEST_QQ_SHARE || resultCode == Constants.REQUEST_QZONE_SHARE || resultCode == Constants.REQUEST_OLD_SHARE) {
                Tencent.handleResultData(data, mIUiListener);
            }
        }
    }

    private class MyIUiListener implements IUiListener {
        @Override
        public void onComplete(Object o) {
            showShortText("分享成功");
        }

        @Override
        public void onError(UiError uiError) {
            showShortText("分享失败");
        }

        @Override
        public void onCancel() {
            showShortText("分享取消");
        }
    }

    @Override
    public void showCommentList(List<HuoDongDetailBean.DataBean.CommentBean> commentBean) {
        commentBeanList.clear();
        commentBeanList.addAll(commentBean);
        mAdapter.notifyDataSetChanged();
    }

    /**
     * 提交评论完成
     *
     * @param bean    活动评论数据
     * @param content 评论内容
     * @param addTime 添加时间
     */
    @Override
    public void submitCommentFinish(HuoDongCommentBean bean, String content, String addTime) {
        // 更改
        HuoDongDetailBean.DataBean.CommentBean commentBean = new HuoDongDetailBean.DataBean.CommentBean();
        commentBean.setId(bean.getData().getNumber());
        commentBean.setContent(content);
        commentBean.setUid(uid);
        commentBean.setPhoto(UserInfoBean.getAvatar(mContext));
        commentBean.setUnit(UserInfoBean.getUniversity(mContext));
        commentBean.setAddTime(addTime);
        commentBean.setName(UserInfoBean.getNickName(mContext));
        commentBean.setThing("0");
        commentBean.setIsThing(0);
        commentBean.setTableType("0");
        commentBeanList.add(0, commentBean);
        mAdapter.notifyDataSetChanged();
        showShortText("发表成功");
    }

    @Override
    public void addReply(ActiveReplyBean bean, String content) {
        HuoDongDetailBean.DataBean.CommentBean commentBean = new HuoDongDetailBean.DataBean.CommentBean();
        commentBean.setTableType("1");
        commentBean.setId(bean.getData().getNumber());
        commentBean.setFName(UserInfoBean.getNickName(mContext));
        commentBean.setFPhoto(UserInfoBean.getAvatar(mContext));
        commentBean.setTName(tName);
        commentBean.setUnit(UserInfoBean.getUniversity(mContext));
        commentBean.setIsThing(0);
        commentBean.setThing("0");
        commentBean.setContent(content);
        commentBean.setAddTime(System.currentTimeMillis() / 1000 + "");
        commentBean.setComment(comment);
        commentBeanList.add(0, commentBean);
        mAdapter.notifyDataSetChanged();
        showShortText("发表成功");
    }

    @Override
    public void showProgress() {
        CustomProgressDialog.showLoading(mContext, "请稍后，正在努力加载...", true);
    }

    @Override
    public void hideProgress() {
        CustomProgressDialog.stopLoading();
    }

    /**
     * 设置当前的关注状态
     * 0 - 未关注
     * 1 - 已关注
     *
     * @param followBean 关注返回结果
     */
    @Override
    public void showFollowed(FollowBean followBean) {
        if (followBean.getCode() == 0) {
            hdAttention.setText("关注");
        } else if (followBean.getCode() == 1) {
            hdAttention.setText("已关注");
        }
    }

    @Override
    public void showToast(String content) {
        showShortText(content);
    }

    @Override
    public void showPraised(HuoDongPraiseBean bean) {
        if (bean.getCode() == 200) {
            //点赞成功
            detailPraise.setCompoundDrawablesWithIntrinsicBounds(isPraised, null, null, null);
            detailPraise.setText("已赞");
        } else {
            detailPraise.setCompoundDrawablesWithIntrinsicBounds(toPraise, null, null, null);
            detailPraise.setText("赞");
        }
    }

    /**
     * 活动收藏结果
     *
     * @param bean 结果
     */
    @Override
    public void shoeActiveCollectResult(HuoDongCollectBean bean) {
        if (bean.getCode() == 200) {
            Drawable followed = ContextCompat.getDrawable(mContext, R.mipmap.y_like);
            if (followed != null) {
                followed.setBounds(0, 0, followed.getMinimumWidth(), followed.getMinimumHeight());
                tvIsFollowed.setCompoundDrawables(null, followed, null, null);
            }
            showShortText("收藏成功");
            tvIsFollowed.setText("已收藏");
        } else {
            Drawable followed = ContextCompat.getDrawable(mContext, R.mipmap.like_gray_solid);
            if (followed != null) {
                followed.setBounds(0, 0, followed.getMinimumWidth(), followed.getMinimumHeight());
                tvIsFollowed.setCompoundDrawables(null, followed, null, null);
            }
            showShortText("已取消");
            tvIsFollowed.setText("收藏");
        }
    }

    @Override
    public void showPraiseCommentResult(HuoDongPraiseBean bean, int position) {
        if (bean.getCode() == 200) {
            commentBeanList.get(position).setIsThing(1);
            commentBeanList.get(position).setThing(bean.getData().getCount() + "");
            mAdapter.notifyItemChanged(position);
        } else if (bean.getCode() == 201) {
            commentBeanList.get(position).setIsThing(0);
            commentBeanList.get(position).setThing(bean.getData().getCount() + "");
            mAdapter.notifyItemChanged(position);
        }
    }

    @Override
    public void firstLoadError(Throwable throwable) {
        if ((retryConnect < 5)) {
            retryConnect++;
            mPresenter.getHuoDongDetail(uid, activityId);
        } else {
            retryConnect = 0;
            showShortText("请求失败");
            finish();
        }
    }

    /**
     * 地图导航选择功能
     */
    private class onClickSheetItem implements ActionSheet.OnSheetItemClickListener {

        private String keyword;

        onClickSheetItem(String keyword) {
            this.keyword = keyword;
        }

        /**
         * 导航选择菜单
         *
         * @param which 条目位置
         */
        @Override
        public void onClick(int which) {
            switch (which) {
                case 1:
                    //腾讯地图
                    Intent toTencentMap = null;
                    String downloadUri = "http://softroute.map.qq.com/downloadfile?cid=00001";
                    String baseUrl = "qqmap://map/";
                    String searchPlace = "search?keyword=" + keyword;
                    if (AppUtils.isAvailable(mContext, "com.tencent.map")) {
                        try {
                            toTencentMap = Intent.parseUri(baseUrl + searchPlace, 0);
                        } catch (URISyntaxException e) {
                            e.printStackTrace();
                        }
                    } else {
                        try {
                            toTencentMap = Intent.parseUri(downloadUri, 0);
                        } catch (URISyntaxException e) {
                            e.printStackTrace();
                        }
                    }
                    startActivity(toTencentMap);
                    break;
                case 2:
                    //百度地图
                    if (AppUtils.isAvailable(mContext, "com.baidu.BaiduMap")) {
                        Intent toBaiduMap = null;
                        try {
                            toBaiduMap = Intent.parseUri("intent://map/place/search?query=" + keyword +
                                    "&src=yourCompanyName|yourAppName#Intent;" +
                                    "scheme=bdapp;package=com.baidu.BaiduMap;end", Intent.URI_INTENT_SCHEME);
                            startActivity(toBaiduMap);
                        } catch (URISyntaxException e) {
                            e.printStackTrace();
                            showShortText("百度地图启动失败");
                        }
                    } else {
                        showShortText("未安装百度地图");
                    }
                    break;
                case 3:
                    //高德地图
                    if (AppUtils.isAvailable(mContext, "com.autonavi.minimap")) {
                        try {
                            Intent toGodMap = new Intent();
                            toGodMap.setAction(Intent.ACTION_VIEW);
                            toGodMap.addCategory(Intent.CATEGORY_DEFAULT);
                            //将功能Scheme以URI的方式传入data
                            Uri uri = Uri.parse("androidamap://poi?sourceApplication=softname&keywords="
                                    + keyword + "&dev=0");
                            toGodMap.setData(uri);
                            startActivity(toGodMap);
                        } catch (Exception e) {
                            showShortText("高德地图启动失败");
                        }
                    } else {
                        showShortText("未安装高德地图");
                    }
                    break;
                default:
                    break;
            }
        }
    }

    @Override
    public void onBackPressed() {

        //如果sku popup window处于弹出状态，将其收起
        if (mTicketSkuPopupWindow != null && mTicketSkuPopupWindow.getPopupWindow().isShowing()) {
            mTicketSkuPopupWindow.dismiss();
            return;
        }

        // 如果表情选择器依然处于弹出状态，将其收起
        if (emotionLayoutIsShow) {
            mEmotionView.setVisibility(View.GONE);
            emotionLayoutIsShow = false;
            return;
        }

        super.onBackPressed();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        CustomProgressDialog.stopLoading();
    }
}
